package com.example.demo.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

@Slf4j
public class ParamsCheck {
    public static boolean ifNullOrEmpty(Object o) {
        if (o == null) {
            return true;
        } else {
            if (o instanceof String) {
                return ((String) o).trim().isEmpty();
            }
            if (o instanceof Collection) {
                return ((Collection<?>) o).isEmpty();
            }
            if (o instanceof Object[]) {
                return ((Object[]) o).length == 0;
            }
        }
        return false;
    }

    public static void checkNullOrEmpty(Object o, String paramName) {
        if (ifNullOrEmpty(o)) {
            throw new IllegalArgumentException(paramName + " is needed");
        }
    }

    public static void checkAllNullOrEmpty(Map<String, Object> params) {
        int flag = 0;
        for (Object o : params.values()) {
            if (ifNullOrEmpty(o)) {
                flag++;
            }
        }
        if (params.size() == flag) {
            throw new IllegalArgumentException("Any of " + params.keySet() + " is needed");
        }
    }

    public static Collection<?> getOutOfRange(Collection<?> collection, Collection<?> range) {
        Collection<Object> res = new ArrayList<>();
        for (Object o : collection) {
            if (!range.contains(o)) {
                res.add(o);
            }
        }
        return res.isEmpty() ? null : res;
    }

    public static void checkInvalidOrders(Collection<String> orderNames, Collection<String> range) {
        Collection<String> res = (Collection<String>) getOutOfRange(orderNames, range);
        if (res != null) {
            String strs = String.join(",", res);
            throw new IllegalArgumentException("Invalid orderNames: " + strs);
        }
    }


    public static void checkInvalidOrders(Collection<String> orderNames, Map<String, String> range) {
        Collection<String> res = (Collection<String>) getOutOfRange(orderNames, range.values());
        if (res != null) {
            String[] resHere = (String[]) replace(res, range);
            String strs = String.join(",", resHere);
            throw new IllegalArgumentException("Invalid orderNames: " + strs);
        }
    }

    public static Object[] replace(Collection<?> origin, Map replaceConf) {
        Collection<Object> res = new ArrayList<>();
        for (Object o : origin) {
            if (replaceConf.containsKey(o)) {
                res.add(replaceConf.get(o));
            } else {
                res.add(o);
            }
        }
        return new Object[]{res};
    }


}
